package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    // 查询vue视图
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    //@Override
    public List<JSONObject> getBaseCategoryList1() {
        // 1. 获取所有分类数据
        List<BaseCategoryView> allCategories = baseCategoryViewMapper.selectList(null);

        // 2. 按一级分类分组
        Map<Long, List<BaseCategoryView>> level1Groups = allCategories.stream()
                .collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        List<JSONObject> result = new ArrayList<>();

        // 3. 处理一级分类
        for (Map.Entry<Long, List<BaseCategoryView>> level1Entry : level1Groups.entrySet()) {
            JSONObject level1Json = new JSONObject();
            level1Json.put("categoryName", level1Entry.getValue().get(0).getCategory1Name());
            level1Json.put("categoryId", level1Entry.getKey());

            // 4. 获取当前一级分类下的所有数据
            List<BaseCategoryView> level1Items = level1Entry.getValue();

            // 5. 按二级分类分组
            Map<Long, List<BaseCategoryView>> level2Groups = level1Items.stream()
                    .collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

            List<JSONObject> level2List = new ArrayList<>();

            // 6. 处理二级分类
            for (Map.Entry<Long, List<BaseCategoryView>> level2Entry : level2Groups.entrySet()) {
                JSONObject level2Json = new JSONObject();
                level2Json.put("categoryName", level2Entry.getValue().get(0).getCategory2Name());
                level2Json.put("categoryId", level2Entry.getKey());

                // 7. 处理三级分类
                List<JSONObject> level3List = level2Entry.getValue().stream()
                        .map(item -> {
                            JSONObject level3Json = new JSONObject();
                            level3Json.put("categoryName", item.getCategory3Name());
                            level3Json.put("categoryId", item.getCategory3Id());
                            return level3Json;
                        })
                        .collect(Collectors.toList());
                level2Json.put("categoryChild", level3List);
                level2List.add(level2Json);
            }

            level1Json.put("categoryChild", level2List);
            result.add(level1Json);
        }

        return result;
    }

    // 自己实现
    public List<JSONObject> getBaseCategoryList() {
        // 1. 查询所有的三级分类列表
        // 定义一级分类列表
        // 2. 根据一级分类id分组 返回map1
        return  baseCategoryViewMapper.selectList(null).stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id)).values().stream().map(list1 -> {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("categoryName", list1.get(0).getCategory1Name());
            jsonObject1.put("categoryId", list1.get(0).getCategory1Id());
            jsonObject1.put("categoryChild",
                    // (list1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id))).values().stream() // 二级分类
                    (list1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id))).values().stream().map(list2 -> {
                        JSONObject jsonObject2 = new JSONObject();
                        jsonObject2.put("categoryName", list2.get(0).getCategory2Name());
                        jsonObject2.put("categoryId", list2.get(0).getCategory2Id());
                        jsonObject2.put("categoryChild", list2.stream().map(
                                obj -> {
                                    JSONObject jsonObject3 = new JSONObject();
                                    jsonObject3.put("categoryName", obj.getCategory3Name());
                                    jsonObject3.put("categoryId", obj.getCategory3Id());
                                    return jsonObject3;
                                }
                        ).collect(Collectors.toList()));
                        return jsonObject2;
                    }).collect(Collectors.toList())
            );
            return jsonObject1;
        }).collect(Collectors.toList());
    }




    @Override
    public List<BaseAttribute> findAttribute(Integer categoryId) {

        return baseAttributeMapper.findAttribute(categoryId);
    }

    @Override
    public BaseCategoryView getBaseCategoryViewByCategory3Id(Long category3Id) {
            BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectOne(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory3Id, category3Id));
        return baseCategoryView;
    }

    // 根据一级分类id查询三级分类列表
    @Override
    public List<BaseCategory3> findCategory3ListBycategory1Id(Long c1Id) {

        // 根据一级分类id查询二级分类id
        List<BaseCategory2> baseCategory2s = baseCategory2Mapper.selectList(new LambdaQueryWrapper<BaseCategory2>()
                .eq(BaseCategory2::getCategory1Id, c1Id).select(BaseCategory2::getId));
        List<Long> c2IdList = baseCategory2s.stream().map(category2 -> {
            return category2.getId();
        }).toList();
        // 根据二级分类id查询三级分类id
        List<BaseCategory3> baseCategory3s = baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>()
                .in(BaseCategory3::getCategory2Id, c2IdList).eq(BaseCategory3::getIsTop, 1).last("limit 7"));
        return baseCategory3s;
    }

    // 根据一级分类查询所有二级分类和三级分类信息
    //JSONObject: categoryName categoryId categoryChild
    @Override
    public JSONObject getBaseCategoryListByc1(Long c1Id) {
        // 1. 查询该一级分类下的所有分类视图（包含二三级分类）
        List<BaseCategoryView> allCategories = baseCategoryViewMapper.selectList(
                new LambdaQueryWrapper<BaseCategoryView>()
                        .eq(BaseCategoryView::getCategory1Id, c1Id)
        );

        // 检查结果是否为空
        if (allCategories.isEmpty()) {
            return new JSONObject()
                    .fluentPut("categoryName", "未知分类")
                    .fluentPut("categoryId", c1Id)
                    .fluentPut("categoryChild", Collections.emptyList());
        }

        // 2. 按二级分类分组
        Map<Long, List<BaseCategoryView>> categoriesByC2 = allCategories.stream()
                .collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

        // 3. 构建二级分类列表
        List<JSONObject> category2List = new ArrayList<>();
        categoriesByC2.forEach((c2Id, c3List) -> {
            // 检查c3List是否为空
            if (!c3List.isEmpty()) {
                JSONObject jsonObject2 = new JSONObject()
                        .fluentPut("categoryName", c3List.get(0).getCategory2Name())
                        .fluentPut("categoryId", c2Id)
                        .fluentPut("categoryChild", c3List.stream()
                                .map(c3 -> new JSONObject()
                                        .fluentPut("categoryName", c3.getCategory3Name())
                                        .fluentPut("categoryId", c3.getCategory3Id())
                                )
                                .collect(Collectors.toList())
                        );
                category2List.add(jsonObject2);
            }
        });

        // 4. 构建最终结果
        return new JSONObject()
                .fluentPut("categoryName", allCategories.get(0).getCategory1Name())
                .fluentPut("categoryId", c1Id)
                .fluentPut("categoryChild", category2List);
    }
}
